'use strict';

const BaseController = require('./base');
const moment = require('moment');
const { createOrderVipRule, notifyRule, queryRule } = require('../validator/order/like');
const { commonErr, success } = require('../extend/helper');
const {Aes: { AesGcm }} = require('wechatpay-axios-plugin');
const { wxpayConfig } = require('../../config/cert/wxpay.config');
const { Logger } = require('egg-logger');

class OrderLikeController extends BaseController {

    /**
     * 购买超喜欢
     */
    async pay() {
        const data = this.ctx.request.body;
        const error = this.app.validator.validate(createOrderVipRule, data);
        error && commonErr({beans: error});
        const userId = await this.userId();
        const user = await this.ctx.model.User.findByPk(userId);
        if (!user) {
            commonErr('用户不存在');
        }
        data.user_id = userId;
        data.order_no = userId + moment().format('YYYYMMDDHHmmss');
        data.total_amount = data.price * data.count;
        console.log(data);
        const order = await this.ctx.model.OrderLike.create(data);
        if (!order) {
            commonErr('创建订单失败');
        }
        //统一下单
        const prepayId = await this.service.likeOrder.jsapi(order, user.wxapp_openid);
        //签名
        const sign = await this.service.wechatPay.sign(prepayId);
        sign.out_trade_no = order.order_no;

        this.ctx.helper.success({bean: sign});
    }

    /**
     * 主动回调
     */
    async query() {
        const data = this.ctx.request.body;
        const error = this.app.validator.validate(queryRule, data);
        error && commonErr({beans: error});
        const res = await this.service.likeOrder.query(data.out_trade_no);
        success()
    }


    /**
     * 自动回调
     * {"remoteIP":"121.51.30.176","originalUrl":"/api/order/vip/notify",
     * "req":{"method":"POST","header":{"Content-Type":"application/json"},"query":{},
     * "body":{"id":"9ff96418-901a-5e2e-bec2-255b0b06d70d","create_time":"2021-05-19T14:38:25+08:00","resource_type":"encrypt-resource","event_type":"TRANSACTION.SUCCESS","summary":"支付成功",
     * "resource":{"original_type":"transaction","algorithm":"AEAD_AES_256_GCM",
     * "ciphertext":"FkAQJbn0ZEPCgO27dItfYnicK3uj21Or3Dz3n3vX0JzLCAxDk8ii8f5m70272Uqq9W2PHQW3owUxer4zJI3Ld9h+goY3CIErEzdKkNmb/bIsLosqz+sKYcaLxaYSMlapd0ZT2ghGRzLoKDauctAqd8B62/PEDf/IvpMhekaNiVlXUiCODMZ0qVLAvV22zGzbubACfIjD+c9KaQLYg23WMLYcPIYGq2+ymJsORv6+0ziVxrCJ5k+G7FmMexE7SvoDCaJS315binFA8JzzgpwRHT41ykCdldNC/ZyATdxN9ZtsjVVV9K67rp51z2zOG1+cyJyw1oY3DgoWvNpgZHd5B2m+3lHSxzr7XsGBotN1Qe8Cdm912YRblg+WiMXysE3Xt8/LGY0X7qf9Zy5DDMPRRoUsWxsy82+nXwiL53vd2WVcS9ENbcbiUoEmNrtxwwHKeJuKVxSK5dQYav70s/fy4xZpT4AbPB8bJxwVXnEAuch0/itONfQUgFryJWlTmswJYgRDUjr6ewZf5WDYsRT8DGTbAbXO9CZR3rOoVfy3ErsmaWtopRxGwE/wqTmHkg==",
     * "associated_data":"transaction","nonce":"GDd5CRSGgv62"}},
     * "requestAt":"2021-05-19 14:38:26 391"},
     * "res":{"status":200,"responsereturnCode":"0000","responseMessage":"操作成功","responseTime":"5.529ms","responseAt":"2021-05-19 14:38:26 396"}}
     */
    async notify() {
        const data = this.ctx.request.body;
        const error = this.app.validator.validate(notifyRule, data);
        error && commonErr({beans: error});
        //解密
        try {
            const res = JSON.parse(AesGcm.decrypt(data.resource.nonce,  wxpayConfig.key, data.resource.ciphertext, data.resource.associated_data));
            if (res && 'trade_state' in res && res.trade_state == 'SUCCESS') {
                console.log(res)
                this.service.likeOrder.updateOrder(res.out_trade_no, res.transaction_id);
            }
        } catch(error) {
            console.log(error)
            commonErr('系统错误，请联系管理员');
        }
        success();
    }

}

module.exports = OrderLikeController;
